<template>
  <div class="app-container">
    <!-- 搜索模块 -->
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="凹陷" prop="dent">
        <el-select v-model="queryParams.dent" filterable placeholder="请选择">
          <el-option
            v-for="(item,index) in dent"
            :key="index"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="井号" prop="wellname">
        <el-select v-model="queryParams.wellname" filterable placeholder="请选择">
          <el-option
            v-for="(item,index) in wellname"
            :key="index"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="年度" prop="year">
        <el-input v-model="queryParams.year" placeholder="年度" size="small" style="width: 240px"  />
      </el-form-item> -->

      <el-form-item label="日期" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 240px" ></el-date-picker>
      </el-form-item>
      <el-form-item label="钻机" prop="rigname">
        <el-input v-model="queryParams.rigname" placeholder="钻机" size="small" style="width: 240px"  />
        <!-- <el-select v-model="queryParams.rig_id" placeholder="钻机" style="width: 100%;">
          <el-option v-for="dict in rigOptions" :key="dict.id" :label="dict.name"
            :value="dict.id" />
        </el-select> -->
      </el-form-item>
      <el-form-item label="井类型" prop="well_type">
        <el-select v-model="queryParams.well_type" placeholder="井类型" size="small" style="width: 240px">
          <el-option key="预探井" label="预探井" value="预探井" />
          <el-option key="评价井" label="评价井" value="评价井" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 图标权限模块 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download" size="mini" @click="downloadData">数据下载
        </el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>
    <!-- 展示模块 -->
    <el-table v-loading="loading" :data="ledgerList" @selection-change="handleSelectionChange" stripe>
      <el-table-column width="70" align="center" />
      <el-table-column prop="region" label="区域" align="center"> </el-table-column>
      <el-table-column prop="dent" label="凹陷" align="center" :show-overflow-tooltip="true" > </el-table-column>
      <el-table-column prop="wellname" label="井号" align="center" :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column prop="rigname" label="钻机" align="center"></el-table-column>
      <!-- <el-table-column prop="ljwcjc" label="累计完成进尺" align="center" :show-overflow-tooltip="true" width="100" ></el-table-column>
      <el-table-column prop="sjjc" label="设计进尺" align="center" :show-overflow-tooltip="true" ></el-table-column> -->
      <el-table-column prop="year" label="统计年度" align="center" :show-overflow-tooltip="true" ></el-table-column>
      <!-- <el-table-column prop="tjndwcjc" label="统计年度完成进尺" align="center" :show-overflow-tooltip="true" ></el-table-column> -->
      <el-table-column prop="zjxxjd" label="钻井形象进度" align="center"  width="100" ></el-table-column>
      <el-table-column prop="zjys" label="钻井预算" align="center"  width="100" ></el-table-column>
      <el-table-column prop="syys" label="试油预算" align="center"  width="130" ></el-table-column>
      <el-table-column prop="tzhj" label="投资合计" align="center"  width="130" ></el-table-column>
      <el-table-column prop="zjxj" label="钻井小计" align="center"  width="130" ></el-table-column>
      <el-table-column prop="yjfjglfxj" label="研究费及管理费小计" align="center"  width="140"></el-table-column>
      <el-table-column prop="syxj" label="试油小计" align="center"  width="130" ></el-table-column>
      <el-table-column prop="zclhtxj" label="钻测录合同小计" align="center"  width="130"></el-table-column>
      <!-- <el-table-column prop="syndwcjc" label="上一年度完成进尺" align="center"></el-table-column> -->
      <el-table-column
        v-if="hasPermi(['admin:approve:form:edit:post', 'system:clearsavefile:download:post', 'admin:budget:form:delete:{id}:delete'])"
        label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-camera"
            @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <el-dialog title="数据详情" :visible.sync="addDataVisible" width="1200px" append-to-body>
      <el-tabs type="border-card" v-model="activeName">
        <el-tab-pane label="井基本信息" name="wellinfo">
          <el-form ref="lrForm" :inline="true" :model="lrForm" :rules="lrRules" label-width="120px">
            <el-form-item label="区域" prop="region">
              <el-input v-model="lrForm.region" placeholder="区域"  style="width: 240px"  disabled/>
            </el-form-item>
            <el-form-item label="凹陷" prop="dent">
              <el-input v-model="lrForm.dent" placeholder="凹陷"  style="width: 240px"  disabled/>
            </el-form-item>
            <el-form-item label="井号" prop="wellname">
              <el-input v-model="lrForm.wellname" placeholder="井号"  style="width: 240px"  disabled/>
            </el-form-item>
            <el-form-item label="井类型" prop="well_type">
              <el-select v-model="lrForm.well_type" placeholder="井类型" size="small" style="width: 240px" disabled>
                <el-option key="预探井" label="预探井" value="预探井" />
                <el-option key="评价井" label="评价井" value="评价井" />
              </el-select>
            </el-form-item>
            <el-form-item label="井深" prop="welldepth">
              <el-input v-model="lrForm.welldepth" placeholder="井深"  type="number" style="width: 240px" disabled/>
            </el-form-item>
            <el-form-item label="项目组" prop="xmz">
              <el-input v-model="lrForm.xmz" placeholder=""  style="width: 240px" disabled/>
            </el-form-item>
            <el-form-item label="钻机" prop="rig_id">
              <el-select v-model="lrForm.rig_id" placeholder="钻机" size="small" style="width: 240px" disabled>
                <el-option v-for="dict in rigOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否核销" prop="ishx">
              <el-select v-model="lrForm.ishx" placeholder="是否核销" size="small" style="width: 240px" disabled>
                <el-option key="拟核销" label="拟核销" value="拟核销" />
                <el-option key="是" label="是" value="是" />
                <el-option key="否" label="否" value="否" />
              </el-select>
            </el-form-item>
            <el-form-item label="开钻日期" prop="kzrq">
              <el-date-picker v-model="lrForm.kzrq" type="date" placeholder="选择日期" format="yyyy.MM.dd" value-format="yyyy.MM.dd" style="width: 240px" disabled> </el-date-picker>
            </el-form-item>
            <el-form-item label="完钻日期" prop="wzrq">
              <el-date-picker v-model="lrForm.wzrq" type="date" placeholder="选择日期" format="yyyy.MM.dd" value-format="yyyy.MM.dd" style="width: 240px" disabled> </el-date-picker>
            </el-form-item>
            <el-form-item label="完井日期" prop="wjrq">
              <el-date-picker v-model="lrForm.wjrq" type="date" placeholder="选择日期" format="yyyy.MM.dd" value-format="yyyy.MM.dd" style="width: 240px" disabled> </el-date-picker>
            </el-form-item>
            <el-form-item label="统计年度" prop="year">
              <el-input v-model="lrForm.year" placeholder="统计年度" type="number"  style="width: 240px" disabled/>
            </el-form-item>
            <el-form-item label="累计完成进尺" prop="ljwcjc">
              <el-input v-model="lrForm.ljwcjc" placeholder="累计完成进尺"  type="number" style="width: 240px" disabled/>
            </el-form-item>
            <el-form-item label="设计进尺" prop="sjjc">
              <el-input v-model="lrForm.sjjc" placeholder="设计进尺"  type="number" style="width: 240px" disabled/>
            </el-form-item>
            <el-form-item label="上年度完成进尺" prop="syndwcjc">
              <el-input v-model="lrForm.syndwcjc" placeholder="上一年度完成进尺"  type="number" style="width: 240px" disabled/>
            </el-form-item>
          </el-form>

          <div style="padding-left:900px" class="dialog-footer">
            <el-button type="primary" @click="addDataVisible=false">确 定</el-button>
            <el-button @click="addDataVisible=false">取 消</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="费用明细" name="costinfo">
          <el-tabs v-model="costdetail">
            <el-tab-pane label="钻井费用" name='zj'>
              <el-table :key="Math.random()" v-loading="loading" :data="costdetailListzj.filter(data => !search || data.cost_name.toLowerCase().includes(search.toLowerCase()))">
                <el-table-column prop="cost_name" label="费用名称" align="center">
                </el-table-column>
                <el-table-column prop="cost_type" label="费用类型" align="center">
                </el-table-column>
                <el-table-column prop="real_cost" label="实际费用" align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.real_cost" placeholder="实际费用" type="number" />
                  </template>
                </el-table-column>
                <el-table-column prop="check_cost" label="已结费用" align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.check_cost" placeholder="已结费用" type="number"/>
                  </template>
                </el-table-column>
                <el-table-column prop="company" label="公司名称"  align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.company" placeholder="公司名称" />
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" align="center">
                  <template slot="header" slot-scope="scope">
                    <el-input
                      v-model="search"
                      size="mini"
                      placeholder="输入关键字搜索"/>
                  </template>
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.remark" placeholder="备注" type="number"/>
                  </template>
                </el-table-column>
              </el-table>
              <div style="padding-left:800px" class="dialog-footer">
                <el-button @click="addDataVisible=false">取 消</el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane label="试油费用" name='sy'>
              <el-table :key="Math.random()" v-loading="loading" :data="costdetailListsy.filter(data => !search || data.cost_name.toLowerCase().includes(search.toLowerCase()))">
                <el-table-column prop="cost_name" label="费用名称" align="center">
                </el-table-column>
                <el-table-column prop="cost_type" label="费用类型" align="center">
                </el-table-column>
                <el-table-column prop="real_cost" label="实际费用" align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.real_cost" placeholder="实际费用" type="number" />
                  </template>
                </el-table-column>
                <el-table-column prop="check_cost" label="已结费用" align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.check_cost" placeholder="已结费用" type="number"/>
                  </template>
                </el-table-column>
                <el-table-column prop="company" label="公司名称"  align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.company" placeholder="公司名称" />
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" align="center">
                  <template slot="header" slot-scope="scope">
                    <el-input
                      v-model="search"
                      size="mini"
                      placeholder="输入关键字搜索"/>
                  </template>
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.remark" placeholder="备注" type="number"/>
                  </template>
                </el-table-column>
              </el-table>
              <div style="padding-left:800px" class="dialog-footer">
                <el-button @click="addDataVisible=false">取 消</el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTypeAll,
  inspectHeaderAll,
  addType,
  dataEche,
  editType,
  delType,
  listCompanyType,
  listRegionType0,
  listRegionType1,
  listRigType,
  addTypeCost,
  listTypeDetail,
  downloadLedger,
  getDictList
} from "@/api/vadmin/budget/ledger/ledgerapi";
import chunkUpload from '@/utils/chunkUpload'
import { getToken } from "@/utils/auth";
import { Decrypt } from "@/utils/AesHmacMD5";

export default {
  name: "statistics",
  data() {
    return {
      // 遮罩层
      loading: true,regionOptions0:[],regionOptions1:[],rigOptions:[],costdetailList:[],costdetailListzj:[],costdetailListsy:[],companyOptions:[],addDataVisible:false,
      selectLedger:{regionname:'',wellname:'',well_type:'',welldepth:'',group:'',rig:'',rigmodel:'',ishx:'',wjzt:''},
      ledgerDict:{'regionname':'区域名称',xmz:'项目组',rig:'钻机',wellname:'井号',welldepth:'井深',ishx:'是否核销',wjzt:'完井状态',
      kzrq:'开钻日期',wzrq:'完钻日期',wjrq:'完井日期',wj:'完井',ljwcjc:'累计完成进尺',sjjc:'设计进尺',year:'统计年度',tjndwcjc:'统计年度完成进尺',syndwcjc:'上一年度完成进尺'},
      // 选中数组
      ids: [],activeName:'wellinfo',costdetail:'zj',
      lrForm:{regionid:'',wellname:'',well_type:'预探井',welldepth:'',group:'',rig_id:'',ishx:'是',kzrq:'',wzrq:'',wjrq:'',year:2024,ljwcjc:'',sjjc:'',syndwcjc:''},
      valNames: [],

      lrRules: {
        regionid: [  { required: true, message: '区域不能为空', trigger: "change" }],
        wellname: [  { required: true, message: '井号不能为空', trigger: "blur" }],
        well_type: [  { required: true, message: '井号不能为空', trigger: "change" }],
        welldepth: [  { required: true, message: '井号不能为空', trigger: "blur" }],
        rig_id:[{ required : true, message: '钻机不能为空', trigger: "change" }],
        ljwcjc:[{ required : true, message: '累计完成进尺不能为空', trigger: "blur" }],
        sjjc:[{ required : true, message: '设计进尺不能为空', trigger: "blur" }],
        syndwcjc:[{ required : true, message: '上一年度完成进尺', trigger: "blur" }],
        // wjrq:[{ type: 'date', required: true, message: '请选择日期', trigger: 'change'  }],
        // kzrq:[{ type: 'date', required: true, message: '请选择日期', trigger: 'change'  }],
        // wzrq:[{ type: 'date', required: true, message: '请选择日期', trigger: 'change'  }],
      },
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 批复表格数据
      ledgerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,openCost:false,openCostdetail:false,
      // 场景数据字典
      sceneOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,  // 当前页数
        pageSize: 10,  // 每页显示几个-------坨深斜3续
        wellname: '',year:'2024',region:'',dent:'',well_type:'',rigname:'',createTime:''
      },
      dent:[], //凹陷
      wellname:[], //井号
      // 表单参数
      form: {},formCost:{},
      // 表单校验
      rules: {
        path: [
          { required: true, validator: this.validatorPath(), trigger: "blur" }
        ]
      },rulesCost:{},
      chunkUpload: chunkUpload, // 文件上传
      uploadUrl: process.env.VUE_APP_BASE_API + '/admin/system/upload_fileM/', //文件上传的路径
      uploadData: {},
      headers: {
        Authorization: "Bearer " + getToken()
      },
    };
  },
  created() {
    let currentDate = new Date();
    let year = currentDate.getFullYear();
    let month = currentDate.getMonth() + 1;  // 注意月份从0开始，需要加1
    let day = currentDate.getDate();
    this.queryParams.createTime=year + "-" + month + "-" + day;
    this.getList();
    this.getDict();
  },
  methods: {
    //查询所有的区域 凹陷 井号
    getDict() {
      console.log('查询所有');
      getDictList(this.addDateRange('aa')).then(response => {
        let res = JSON.parse(Decrypt(response.data));
        //区域数组
        this.region = res.region.flat();
        //凹陷数组
        this.dent = res.dent.flat();
        //井号数组
        this.wellname = res.wellname.flat();

      })
    },
    validatorPath() {
      return (rule, value, callback) => {
        if (this.form.id == undefined && !value) {
          return callback(new Error("模板文件不能为空"));
        } else {
          callback();
        }
      }
    },
    /** 查询数字台账列表 */
    getList() {
      this.loading = true;
      var _this=this
      listTypeAll(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        var resData = JSON.parse(Decrypt(response.data))
        this.ledgerList = resData.results;
        this.total = resData.count;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        scene: undefined,
        path: undefined,
      };
      this.formCost={
        path: undefined
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //数据下载
    downloadData(){
      var ledgerids=[]
      for (var i = 0; i < this.ledgerList.length; i++) {
        ledgerids.push(this.ledgerList[i].id)
      }
      downloadLedger(this.addDateRange({ledgerids:ledgerids,pageSize:1000,pageNum:1}, this.dateRange)).then(response => {
        var resData = JSON.parse(Decrypt(response.data))
        var costList = resData.data;
        debugger
        var fileName = "data.csv"; //使用当前时间戳作为文件名
        var columnDelimiter = ","; //列分割符
        var lineDelimiter = "\r\n"; //行分割符
        var keyValue=resData.downloadStr
        let result = ""; // 最终结果的字符串
        for(var i=0;i<keyValue.length;i++){
          result +=this.transferred(keyValue[i]) +columnDelimiter;
        }
        result += lineDelimiter;
        for (var i = 0; i < costList.length; i++) {
          for(var j=0;j<keyValue.length;j++){
            console.log(costList[i][keyValue[j]])
            result +=this.transferred(costList[i][keyValue[j]]==undefined ? '': costList[i][keyValue[j]]+'') +columnDelimiter;
          }
          result += lineDelimiter;
        }
        this.downCsvFile(fileName,result)
        // this.total = resData.count;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$refs.uploadRef.clearFiles()
    },
     /** 数字台账新增 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this, this.form.id == undefined) {
            addType(this.form).then(response => {
              this.msgSuccess(response.msg);
              this.open = false;
              this.getList();
            });
          } else {
            editType(this.form).then(response => {
              this.msgSuccess(response.msg);
              this.open = false;
              this.getList();
            })
          }
        }
      });
    },
    submitCostForm(){
      this.$refs["formCost"].validate(valid => {
        if (valid) {
          if (this, this.formCost.id == undefined) {
            addTypeCost(this.form).then(response => {
              this.msgSuccess(response.msg);
              this.openCost = false;
              this.getList();
            });
          } else {

          }
        }
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.valNames = selection.map(item => item.formCode);
      this.single = selection.length !== 1;
      this.multiple = selection.length < 2;
    },
    /** 详情按钮操作 */
    handleDetail(row){
      debugger
      this.addDataVisible=true;
      this.lrForm=row;
      this.lrForm.id==''
      const ids = row.id || this.ids;
      listTypeDetail(this.addDateRange({ledgerid:ids,pageSize:1000,pageNum:1}, this.dateRange)).then(response => {
        var resData = JSON.parse(Decrypt(response.data))
        this.costdetailList = resData.results;
        this.costdetailListzj = [];
        this.costdetailListsy = [];
        for(var k=0;k<this.costdetailList.length;k++){
          if(this.costdetailList[k].cost_type=='钻井'||this.costdetailList[k].cost_type=='研究费及管理费'){
            this.costdetailListzj.push(this.costdetailList[k])
          }else if(this.costdetailList[k].cost_type=='试油'){
            this.costdetailListsy.push(this.costdetailList[k])
          }
        }
        // this.total = resData.count;
        this.loading = false;
      });
    },
    // 场景字典翻译
    sceneFormat(row, column) {
      return this.selectDictLabel(this.sceneOptions, row.scene);
    },
    /** 文件下载 **/
    handleDownload(row) {
      this.download(row.path, row.name);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // const id = row.id || this.ids;
      dataEche({ "id": row.id }).then((response) => {
        this.form = JSON.parse(Decrypt(response.data));
        this.open = true;
        this.title = "模板修改";
      });
    },
    /** 文件上传成功调用的钩子函数 */
    handleSuccess(data) {
      this.form.path = data.saveFile
      this.formCost.path = data.saveFile
      this.$message.success('文件上传成功！');
      // inspectHeaderAll({ 'path': data.saveFile }).then(response => {
      //   var resData = JSON.parse(Decrypt(response.data))
      //   if (resData.bol) {
      //     this.form.path = data.saveFile
      //     this.$message.success('文件上传成功！');
      //     this.$refs.uploadRef.clearFiles()
      //   } else {
      //     this.onInspect(resData.repeat_values)
      //   }
      // })

    },
    /** 文件上传失败调用的钩子函数 */
    onError() {
      this.form.path = undefined
      this.$message.error('文件上传失败！');
      this.$refs.uploadRef.clearFiles()
    },
    /** 重复列回显函数 */
    onInspect(data) {
      this.form.path = undefined
      this.$message.error('文件' + data + '列重复，请检查之后重新上传！');
      this.$refs.uploadRef.clearFiles()
    },
    transferred(data) {
      return data.replace(/<br>/g, "\r\n").replace(/&gt;/g, ">");
    },
    downCsvFile(fileName, result) {
      var fileName = fileName; //使用当前时间戳作为文件名
      var blob = new Blob(["\uFEFF" + result], { type: "text/csv;" }); //记得将编码格式设置一下，避免最终下载的文件出现乱码
      var downloadLink = document.createElement("a");
      if ("download" in downloadLink) {
        var url = URL.createObjectURL(blob);
        downloadLink.href = url;
        downloadLink.download = fileName;
        downloadLink.hidden = true;
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
      } else {
        if (navigator.msSaveBlob) {
          //IE10+
          navigator.msSaveBlob(blob, fileName);
        }
      }
    },
  }
};
</script>
   <style scoped>
/* ::v-deep .el-table th.el-table__cell > .cell {
    display: inline-block;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    position: relative;
    vertical-align: middle;
    padding-left: 10px;
    padding-right: 10px;
    width: 100%;
    white-space: nowrap !important; */
/* } */

  </style>
